import Global from '../global/global.js'
/**
 * 怪物类
 */
export default class Npc {
  constructor () {
    this.npcList = []
  }

  /**
   * 根据坐标将图形画到页面上
   */
  draw(ctx) {
    let random = Math.floor(Math.random() * 60 + 60)
    if (random % 60 == 0) {
      // 随机生成怪物数量
      this.npcList.push({
        x: this.randomNpcX(),
        y: -60,
        width: 80,
        height: 60,
        color: '#00CCFF',
        imgName: 'npc',
        centerX: 80 / 2,
        centerY: 60 / 2,
        direction: this.randomNpxGoX()
      })
    }

    // 循环npc列表
    for (let i = this.npcList.length -1; i >= 0; i--) {
      // 超过屏幕 还原位置
      if (this.npcList[i].y > canvas.height) {
        this.npcList.splice(i, 1)
        return
      }

      if (!Global.overGame) {
        // 敌人左右超过屏幕则修改x轴方向
        if (this.npcList[i].direction == 'left') {
          this.npcList[i].x--
          if (this.npcList[i].x - this.npcList[i].centerX <= 0) {
            this.npcList[i].direction = 'right'
          }
        } else if (this.npcList[i].direction == 'right') {
          this.npcList[i].x++
          if (this.npcList[i].x + this.npcList[i].centerX >= canvas.width) {
            this.npcList[i].direction = 'left'
          }
        }
        // 爆炸效果不移动
        if (this.npcList[i].imgName != 'boom') {
          this.npcList[i].y++
        }
      }

      let npcObj = this.npcList[i]
      let w = npcObj.width, h = npcObj.height

      let x = npcObj.x - npcObj.centerX
      let imgObj = Global._ImgObj[npcObj.imgName]
      if (imgObj && npcObj.imgName == 'npc') {
        // ctx.fillStyle = npcObj.color
        // ctx.fillRect(x < 0 ? 0 : x, npcObj.y, w, h)
        ctx.drawImage(imgObj, 32, 55, w + 55, h + 23, x < 0 ? 0 : x, npcObj.y, w, h);
      } else {
        ctx.drawImage(imgObj, 100, 88, npcObj.width, npcObj.height, x < 0 ? 0 : x, npcObj.y, npcObj.width, npcObj.height);
      }
    }
  }

  /**
   * 随机怪物X轴位置
   */
  randomNpcX () {
    return Math.random() * (canvas.width - 1) + 1;
  }

  /**
   * 随机怪物行进方向
   */
  randomNpxGoX() {
    let x = parseInt(Math.random() * 9 + 1);
    if (x <= 3) {
      return 'left'
    } else if (x <= 7) {
      return ''
    } else {
      return 'right'
    }
  }

  /**
   * 增加npc死亡效果
   */
  deathEffect(npcX, npcY) {
    this.npcList.push({
      x: npcX,
      y: npcY,
      width: 60,
      height: 60,
      imgName: 'boom',
      color: 'red',
      centerX: 60 / 2,
      centerY: 60 / 2,
      timestemp: new Date().getTime()
    })
  }
}